/*
 * @Author: yan_hai_dong 891236760@qq.com
 * @Date: 2022-10-24 15:25:19
 * @LastEditors: yan_hai_dong 891236760@qq.com
 * @LastEditTime: 2022-10-24 17:27:28
 * @FilePath: \app\src\views\canvas\circle\pie\js\pie.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Base from "../../js/base.js"
export default class Pie extends Base {
    constructor(cvs, hollow = false) {
        super(cvs)
        let {
            ctx
        } = this

        ctx.lineWidth = 0
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'

        this.hollow = hollow

    }
    init(data) {

        let sum = data.reduce((a, b) => a + b.rate, 0)
        data.forEach(v => {
            v.runRate = 10
            v.step = v.rate / sum
        })
        this.data = data

        this.render()
    }
    render() {
        let {
            ctx,
            data,
            cvs,
            hollow,
            lineHeight
        } = this
        const r = cvs.width / 2

        ctx.fillStyle = '#eeeeee';
        ctx.strokeStyle = '#ffffff';
        ctx.beginPath();
        ctx.moveTo(r, r);
        ctx.arc(r, r, r, 0, Math.PI / 180 * 360);
        // 再到终点，再闭合 （结束绘制路径）
        ctx.closePath();
        ctx.fill();
        ctx.stroke();

        data.forEach((v, i) => {
            ctx.fillStyle = v.color;
            ctx.strokeStyle = v.color;
            ctx.beginPath();
            ctx.moveTo(r, r);
            const start = data.slice(0, i).reduce((a, b) => a + b.step, 0)
            ctx.arc(r, r, r, Math.PI / 180 * (360 * start), Math.PI / 180 * (360 * (v.runRate / 100 + start)));
            // 再到终点，再闭合 （结束绘制路径）
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
            if (v.runRate > v.step * 100) {
                v.runRate = v.step * 100
            } else if (v.runRate < v.step * 100) {
                v.runRate += v.step
            }
        });

        if (this.hollow) {
            ctx.fillStyle = '#eeeeee';
            ctx.strokeStyle = '#ffffff00';
            ctx.beginPath();
            ctx.moveTo(r, r);
            ctx.arc(r, r, hollow, 0, Math.PI / 180 * 360);
            // 再到终点，再闭合 （结束绘制路径）
            ctx.closePath();
            ctx.fill();
            ctx.stroke();

            data.forEach((v, i) => {
                ctx.fillStyle = v.color
                ctx.fillText(`${v.text}: ${v.rate.toFixed(0)}%`, cvs.width / 2, i * lineHeight + (cvs.height - lineHeight * data.length) / 2 + lineHeight / 2)
            })
        }
        requestAnimationFrame(this.render.bind(this))
    }
}